package com.tronsis.distribution.activity.training;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.imagepicker.bean.ImageItem;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.CourseBean;
import com.tronsis.distribution.biz.factory.TeamBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.library.activity.BaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.KeyboardUtils;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CourseActivity extends BaseActivity {
    @BindView(R.id.rv_course)
    RecyclerView mRvCourse;
    @BindView(R.id.srl_course)
    SwipeRefreshLayout mSrl;

    @BindView(R.id.ibtn_back)
    ImageButton ibtnBack;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.ib_clear)
    ImageButton ibClear;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;


    private CommonAdapter<CourseBean> mCourseAdapter;
    private List<CourseBean> mCourseList = new ArrayList<>();

    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;
    private String mSearch;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course);
        ButterKnife.bind(this);
        setStatusBarUpperAPI21();
        initView();
        initCourseRv();
        httpMyCourse(mPage, mSize, true);
    }

    private void initView() {
        tvTitle.setText("我的课程");
        ibtnRight.setVisibility(View.VISIBLE);
        ibtnBack.setVisibility(View.VISIBLE);

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchClick();
                    return true;
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    ibClear.setVisibility(View.VISIBLE);
                } else {
                    ibClear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick(R.id.ibtn_back)
    void onBackClick() {
        finish();
    }

    @OnClick(R.id.iv_search)
    void searchClick() {
        mSearch = etSearch.getText().toString();
        KeyboardUtils.hideSoftInput(etSearch);
        httpMyCourse(mPage = 1, mSize, true);
    }

    @OnClick(R.id.ib_clear)
    void etClearClick() {
        etSearch.setText("");
    }


    @OnClick(R.id.tv_right)
    void searchCancelClick() {
        llSearch.setVisibility(View.GONE);
        ibtnRight.setVisibility(View.VISIBLE);
        ibtnBack.setVisibility(View.VISIBLE);
        tvRight.setVisibility(View.GONE);
        mSearch = null;
        etSearch.setText(null);
        KeyboardUtils.hideSoftInput(etSearch);
        httpMyCourse(mPage = 1, mSize, true);
    }

    @OnClick(R.id.ibtn_right)
    void searchShowClick() {
        llSearch.setVisibility(View.VISIBLE);
        ibtnRight.setVisibility(View.GONE);
        ibtnBack.setVisibility(View.GONE);
        tvRight.setVisibility(View.VISIBLE);
        mSearch = null;
        etSearch.setText(null);
        KeyboardUtils.hideSoftInput(etSearch);
    }

    private void initCourseRv() {
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                httpMyCourse(mPage, mSize, true);
            }
        });
        mCourseAdapter = new CommonAdapter<CourseBean>(mContext, mCourseList, R.layout.item_course) {
            @Override
            protected void convert(ViewHolder holder, CourseBean courseBean, int position) {
                String url = "";
                ArrayList<ImageItem> list = CommonUtil.getSplitImage(courseBean.getImageFid());
                if (list.size() > 0) {
                    url = list.get(0).url;
                }
                holder.setImageByUrl(mContext, R.id.iv_cover, url);
                holder.setText(R.id.tv_name, getString(R.string.format_create_name, courseBean.getCreatorName()));
                holder.setText(R.id.tv_course, courseBean.getName());
                holder.setText(R.id.tv_createdOn, getString(R.string.format_time, DateUtil.getDateTimeString(courseBean.getCreatedOn())));
            }
        };

        mCourseAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, CourseDetailActivity.class);
                intent.putExtra("courseId", mCourseList.get(position).getCourseId());
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mLoadMoreWrapper = new LoadMoreWrapper(mCourseAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mCourseList.size() % 15 == 0 && mCourseList.size() > 0 && mCourseList.size() < mTotal) {
                    mPage = (mCourseList.size() / 15) + 1;
                    httpMyCourse(mPage, mSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvCourse.addItemDecoration(decoration);
        mRvCourse.setLayoutManager(new LinearLayoutManager(mContext));
        mRvCourse.setAdapter(mLoadMoreWrapper);
    }


    private void httpMyCourse(int page, int size, final boolean isRefresh) {
        if (isRefresh) {
            page = 1;
        }
        try {

            TeamBizFactory.createBiz().listMyCourse(this, page, size, mSearch,new UICallBack() {
                @Override
                public void onStart() {
                    mSrl.setRefreshing(true);
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    List<CourseBean> list = listBean.getList();
                    if (isRefresh) {
                        mCourseList.clear();
                        mCourseList.addAll(list);
                    } else {
                        mCourseList.addAll(list);
                    }
                    mTotal = listBean.getTotal();
                    mLoadMoreWrapper.notifyDataSetChanged();

                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);
                }
            });

        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }
}
